﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using PBO.Data;
using PBO.Data.SQLite;
using PBO.Data.SQLite.DAL;
using PBO.Util;

namespace PBO.Forms.DataForm
{
    public partial class FrmDataDex : Form
    {

        public FrmDataDex()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.PokemonBall;
        }

        private void FrmDataDex_Load(object sender, EventArgs e)
        {
            var ldgv = learnGridView.MoveGrid;
            string[] Hide_Column = { "MvColId", "MvColPower", "MvColAcc", "MvColPP", "MvColTarget" };
            foreach (string col in Hide_Column)
            {
                ldgv.Columns[col].Visible = false;
            }
            this.nudNo.ValueChanged += (s, ea) => BindPokemon();

            BindPokemon();
            BindDataTable();
            BindMoves();
        }

        #region Instance

        private static FrmDataDex instance;

        public static FrmDataDex GetInstance()
        {
            if (instance == null || instance.IsDisposed)
                instance = new FrmDataDex();
            instance.MdiParent = MainForm.GetInstance();
            return instance;
        }

        internal static object GetInstance(Form form)
        {
            if (instance == null || instance.IsDisposed)
                instance = new FrmDataDex();
            instance.MdiParent = form;
            return instance;
        }

        #endregion

        #region Move

        private void BindMoves()
        {
            var dgv = this.moveGridView1.MoveGrid;
            dgv.DataSource = DALDataDex.GetMoveGird("1=1");
            dgv.Columns["MvColLearnBy"].Visible = false;
            dgv.SelectionChanged += MoveGrid_SelectionChanged;
        }

        private void MoveGrid_SelectionChanged(object sender, EventArgs e)
        {
            var dgv = this.moveGridView1.MoveGrid;
            var row = dgv.CurrentRow;
            if (row != null)
            {
                this.txtInfo.Text = row.Cells["MvColInfo"].Value.ToString();
            }
        }

        private void cmdSearchMove_Click(object sender, EventArgs e)
        {

        }

        #endregion

        #region pokemon

        private List<PokemonData> pokemons;
        private int selected_form = 0;

        private void BindPokemon()
        {
            this.pokemons = SQLiteHelper.Pokemon.GetByNumber((int)nudNo.Value);
            if (pokemons == null || pokemons.Count == 0) return;
            var pm = pokemons.First();
            cmdChange.Visible = this.pokemons.Count > 1;
            selected_form = 0;
            BindPokemon(pm);
        }

        private void BindPokemon(PokemonData pm)
        {
            picBase.Image = GetBaseImage(pm.BaseStats);
            SetPokemonImage(pm);

            lblPMName.Text = "名称 :" + pm.NameBase;
            lblPMType.Text = "属性 :" + pm.Type1.ToCnName();
            if (pm.Type2 != BattleType.None)
                lblPMType.Text += "/" + pm.Type2.ToCnName();
            lblTrait.Text = "特性 :" + string.Join("/", pm.Abilities.Select(a => a.Name).ToArray());
            lblWeight.Text = "体重 :" + pm.Weight + "kg";

            lblGender.Text = "性别限制 :";
            switch (pm.GenderRestriction)
            {
                case PokemonGenderRestriction.No:
                    lblGender.Text += "无";
                    break;
                case PokemonGenderRestriction.MaleOnly:
                    lblGender.Text += "公";
                    break;
                case PokemonGenderRestriction.FemaleOnly:
                    lblGender.Text += "母";
                    break;
                case PokemonGenderRestriction.NoGender:
                    lblGender.Text += "无性别";
                    break;
            }

            lblEggGroup.Text = "生蛋组别 :" + string.Join("/", pm.EggGroups.Select(e => e.ToString()).ToArray());
            lblCount.Text = "对战统计 :" + pm.UsageCount;
            var dgv = learnGridView.MoveGrid;
            dgv.DataSource = DALDataDex.GetLearnGrid(pm.Id);
            //SetTree(pm);
        }

        private void SetPokemonImage(PokemonData data)
        {
            picFront1.Image = GameService.GetImage(data.Id, data.FrontImage);
            picFrame1.Image = GameService.GetImage(data.Id, data.Frame);
            picBack1.Image = GameService.GetImage(data.Id, data.BackImage);
            picFront2.Image = GameService.GetImage(data.Id, data.FrontImageF);
            picFrame2.Image = GameService.GetImage(data.Id, data.FrameF);
            picBack2.Image = GameService.GetImage(data.Id, data.BackImageF);
        }

        /// <summary>
        /// 多形态
        /// </summary>
        private void cmdChange_Click(object sender, EventArgs e)
        {
            if (this.pokemons == null || this.pokemons.Count < 2) return;
            if (selected_form < this.pokemons.Count - 1)
                selected_form++;
            else
                selected_form = 0;
            var pm = this.pokemons[selected_form];
            BindPokemon(pm);
        }

        private static Image GetBaseImage(BaseStats bv)
        {
            Bitmap newImg = new Bitmap(325, 160);
            Graphics graph = Graphics.FromImage(newImg);
            Font font = new Font("宋体", 12, FontStyle.Regular, GraphicsUnit.Pixel);
            var arr = bv.ToArray();
            string[] str6d = { "HP", "物攻", "物防", "速度", "特攻", "特防" };
            for (int i = 0; i < arr.Length; i++)
            {
                var rect = new Rectangle(25 + i * 50, 140 - arr[i] / 2, 25, arr[i] / 2);
                graph.FillRectangle(Brushes.DarkRed, rect);
                graph.DrawString(arr[i].ToString(), font, Brushes.Black, 30 + i * 50, 128 - rect.Height);
                graph.DrawString(str6d[i], font, Brushes.Black, i == 0 ? 30 : 25 + i * 50, 148);
            }
            return newImg;
        }

        //private void SetTree(PokemonData data)
        //{
        //    if (treEvolution.Nodes.Count > 0 && data.NameBase == treEvolution.Nodes[0].Text)
        //        return;
        //    treEvolution.Nodes.Clear();

        //    TreeNode newNode = new TreeNode(data.NameBase);
        //    newNode.Tag = data.Id;
        //    treEvolution.Nodes.Add(newNode);

        //    foreach (int no in data.AfterEvolution)
        //    {
        //        SetNodes(no, treEvolution.Nodes[0]);
        //    }
        //    treEvolution.ExpandAll();
        //}

        //private void SetNodes(int identity, TreeNode node)
        //{
        //    var data = BattleData.GetPokemon(identity);
        //    TreeNode newNode = new TreeNode(data.NameBase);
        //    newNode.Tag = data.Id;
        //    node.Nodes.Add(newNode);

        //    foreach (int no in data.AfterEvolution)
        //    {
        //        SetNodes(no, newNode);
        //    }
        //}

        #endregion

        #region event

        private void CounterButton_Click(object sender, EventArgs e)
        {
            var path = FileHelper.SaveFilePath("CSV (逗号分隔)(*.csv)|*.csv");
            if (path.Length > 0)
            {
                var dt = SQLiteHelper.Pokemon.GetCounter();
                FileHelper.WriteToFile(path, dt);
                var result = MessageBox.Show("已保存!是否清空计数器?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (result == DialogResult.Yes)
                {
                    SQLiteHelper.Pokemon.ClearCounter();
                }
            }
        }

        private void cmdClose_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void FrmDataDex_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason != CloseReason.MdiFormClosing)
            {
                e.Cancel = true;
                this.Hide();
            }
        }

        #endregion

        #region BindDataTable

        private void BindDataTable()
        {
            dgvAbilitiy.DataSource = DALDataDex.GetAbilities();
            dgvItem.DataSource = DALDataDex.GetItems();
        }

        private void dgvAbilitiy_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            var dgv = (DataGridView)sender;
            var name = dgv.SelectedRows[0].Cells[1].Value.ToString();
            //System.Diagnostics.Process.Start("http://wiki.52poke.com/wiki/" + name);
        }

        #endregion

    }
}
